package com.indictor.conf;


import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;

/**
 * 有问题的获取资源
 */
public final class RedisConfig {

    private RedisProperties redisProperties;
    private RedisClient client;
    private static RedisConfig redisConfig = new RedisConfig();
    private Queue<RedisCommands<String, String>> redisCommandsSet = new ArrayDeque<>();

    private RedisConfig() {
        init(null);
    }

    public static RedisConfig getInstance() {
        return redisConfig;
    }

    private void setProperties(RedisProperties redisProperties) {
        if (redisProperties == null) {
            this.redisProperties = redisProperties;
        }
    }

    public void init(RedisProperties redisProperties) {
        setProperties(redisProperties);
        if (client == null) {
            RedisURI redisURI = RedisURI.builder().withHost("localhost").withPort(6379).build();
            client = RedisClient.create(redisURI);
        }

    }

    public synchronized RedisCommands get() {
        if (redisCommandsSet.isEmpty()) {
            return addConnection();
        }
        for (RedisCommands<String, String> redisCommands : redisCommandsSet) {
            if (redisCommands.isOpen()) {
                return redisCommands;
            }
        }
        return addConnection();
    }


    private RedisCommands getConnection() {
        StatefulRedisConnection<String, String> redisConnection = client.connect();
        RedisCommands<String, String> redisCommands = redisConnection.sync();
        return redisCommands;
    }

    private RedisCommands addConnection() {
        RedisCommands connection = getConnection();
        redisCommandsSet.add(connection);
        return connection;
    }


}
